import json
import os
import random
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.core.mail import send_mail
from django.shortcuts import render,redirect
from django.urls import reverse
from django.views import View
from courses.models import Course
from operation.models import UserCourse, UserFavorite, UserMessage
from organization.models import CourseOrg
from users.models import Banner, UserProfile
from users.forms import RegisterForm,LoginForm,ForgetForm,ModifyPwdForm,UserInfoForm,UploadImageForm
from django.http import HttpResponse,JsonResponse
from users.utils import SecretOauth
from utils.mixin_utils import LoginRequiredMixin
from PIL import Image
from django.conf import settings
# 1.首页的内容
class IndexView(View):
    def get(self,request):
        all_banners = Banner.objects.filter(id=1)
        banner_courses = Course.objects.all()
        course_orgs = CourseOrg.objects.all()


        return render(request, 'index.html', {
            'all_banners': all_banners,
            'courses': banner_courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
            "MEDIA_URL":'/media/'
        })

# 2.用户注册的页面
class UserRegister(View):
    def get(self, request):

        # 生成表单对象
        register_form = RegisterForm()
        # 调用模版渲染生成表单
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        # 1、获取前端传递的表单数据
        print('---------1-----------')
        data = request.POST
        # 2、验证表单数据
        register_form = RegisterForm(data)
        res = register_form.is_valid()  # 验证成功返回True，验证失败返回False
        if res:
            # 验证成功，则执行相应业务逻辑操作，这里就直接返回验证成功后的字段数据
            # 获取验证成功后的字段

            username = register_form.cleaned_data['email']
            email = register_form.cleaned_data['email']
            password = register_form.cleaned_data['password']
            try:
                user = UserProfile.objects.create_user(username=username,email=email,password=password)
            except Exception as e:
                print('数据库保存失败')
                # 验证失败，则在注册模板中通过register_form.errors获取错误
                return render(request, 'register.html', {'register_form.errors': register_form.errors})

            response = render(request,'index.html')
            response.set_cookie('username',username)
            login(request, user)
            return response
        return render(request, 'register.html', {'register_form.errors': register_form.errors})
# 3.用户登陆页面
class LoginView(View):
    def get(self,request):
        login_form = LoginForm()

        return render(request, 'login.html',{'login_form':login_form})

    def post(self,request):
        data = request.POST
        # 2、验证表单数据
        login_form = LoginForm(data)
        username = data.get("username")
        password = data.get("password")
        # ret = login_form.is_valid()

        # 判断用户是否在数据库中
        try:
            user = authenticate(username=username,password=password)
        except Exception as e:
            return render(request, 'login.html', {'form_errors': login_form.errors})

        if user is not None:
            # 验证成功，则执行相应业务逻辑操作，这里就直接返回验证成功后的字段数据
            response = redirect(reverse("index"))
            response.set_cookie('username',username)
            login(request, user)
            return response
        else:
            # 验证失败，则在注册模板中通过register_form.errors获取错误
            return render(request, 'login.html', {'form_errors': login_form.errors})

# 4.用户忘记密码
class ForgetPwdView(View):
    def get(self,request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})
    def post(self,request):
        data = request.POST
        forget_form = ForgetForm(data)
        # 生成一个随机的六位数存储
        send_data = '%d'%random.randint(100000,999999)
        response = render(request, 'send_success.html')
        if forget_form.is_valid():
            active_code = SecretOauth().dumps(send_data)
            response.set_cookie('active_code', active_code)
            verify_url = 'www.boxuegu.site:8000/reset/' + active_code +'/'
            to_email = forget_form.cleaned_data['email']
            try:
                UserProfile.objects.get(email=to_email)
            except Exception as e:
                print(e)
                return HttpResponse("没有该邮箱")

            subject = "博学谷邮箱验证"
            html_message = '<p>尊敬的用户您好！</p>' \
                           '<p>感谢您使用博学谷</p>' \
                           '<p>请点击此链接更改您的密码：</p>' \
                           '<p><a href="%s">"%s"<a></p>' % (to_email, verify_url)
            send_mail(subject, "", settings.EMAIL_FROM, [to_email], html_message=html_message)
            return response
        return render(request, 'forgetpwd.html', {'forget_form.errors': forget_form.errors})

# 5.用户修改密码
class ResetView(View):
    def get(self,request,active_code):
        # 解密
        userprofile =request.user
        send_data = request.COOKIES.get("active_code")

        active_code = SecretOauth().loads(active_code)
        send_data = SecretOauth().loads(send_data)
        email = userprofile.email
        # 验证成功
        if active_code == send_data:
            response = render(request, 'password_reset.html', {'email': email})
            # response.delete_cookie("active_code",active_code)
            return response
         # 验证失败
        else:
            return render(request, 'active_fail.html')

   # 修改密码

# 6.修改密码成功跳转login
class ModifyPwd(View):

    def post(self,request):
        data = request.POST
        modify_form = ModifyPwdForm(data)
        if modify_form.is_valid():
            password = modify_form.cleaned_data['password1']
            email = request.POST.get("email")
            userprofile = UserProfile.objects.get(email=email)
            userprofile.set_password(password)
            userprofile.save()
            return render(request,'login.html')
        return render(request, 'password_reset.html', {'modify_form.errors': modify_form.errors})

# 7.用户中心--->个人中心------>个人资料
class UserInfo(View):
    def get(self,request):
        user = request.user
        return render(request, 'usercenter-info.html',{"user":user})
    def post(self,request):
        user = request.user
        nick_name = request.POST.get('nick_name')
        birthday = request.POST.get('birthday')
        address = request.POST.get('address')
        mobile = request.POST.get('mobile')
        UserProfile.objects.filter(id=user.id).update(
            birthday=birthday,
            nick_name=nick_name,
            address=address,
            mobile=mobile,
        )
        context = {
            "status": "success",}
        return JsonResponse({"content":context})

# 8.用户中心--->个人中心------>个人资料------>修改头像
class UploadImageView(LoginRequiredMixin,View):
    def post(self,request):
        # user = request.user
        # # 获取图片的名字
        # data = request.FILES.get('image')
        # # 判断是否是正确的image
        # upload_imageform = UploadImageForm(data)
        # ret = upload_imageform.is_valid()
        # if ret:
        #     image_address = UserProfile.objects.get(id=user.id).image
        #     # path1,path2 =os.path.split(str(image_address))
        #     path = '/media/image/2019/04' + '/' + str(data)
        #     UserProfile.objects.filter(id=user.id).update(image=path)
        #     return JsonResponse({
        #           "status":"success",
        #           "msg":'头像修改成功'
        #         })
        # return JsonResponse({
        #           "status":"error",
        #           "msg":'修改头像失败'
        #         })
        data = request.POST
        upload_imageform = UploadImageForm(data,request.FILES)
        res = upload_imageform.is_valid()
        image_url = upload_imageform.cleaned_data['image']
        # dest = os.path.join(settings.MEDIA_ROOT, image_url)
        print('------1-------')
        # print(dest)
        if res:
            user = request.user
            userprofile = UserProfile.objects.get(username=user.username)
            userprofile.image = image_url
            userprofile.save()

            return JsonResponse({
                  "status":"success",
                  "msg":'头像修改成功'
                })
        return JsonResponse({
                  "status":"error",
                  "msg":'修改头像失败'
                })

# 9.用户中心--->个人中心------->我的课程
class MyCourseView(View):
    def get(self,request):

        user_courses = UserCourse.objects.all()
        return render(request, 'usercenter-mycourse.html', {
            'user_courses': user_courses,
        })

# 10.用户中心--->个人中心------->我的收藏
class MyFavOrgView(View):
    def get(self,request):

        org_list = UserFavorite.objects.all()
        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
        })

# 11.用户中心--->个人中心------->我的消息
class MyMessage(View):
    def get(self,request):
        messages = UserMessage.objects.all()
        return render(request, 'usercenter-message.html', {
            'messages': messages,
        })

# 12.退出用户中心
class LogoutView(LoginRequiredMixin,View):
    def get(self,request):
        logout(request)
        # 退出登录，重定向到登录页
        response = redirect(reverse('index'))
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response